<script setup>
import { onMounted, ref, computed } from 'vue'
import { useCartStore } from '@/stores/cart'
import { listCart } from '@/services/cart'
import { useRouter } from 'vue-router'

const cart = useCartStore()
const loading = ref(false)
const selectedIds = ref(new Set())
const router = useRouter()

// 计算属性：是否全选
const isAllSelected = computed(() => {
  return cart.items.length > 0 && selectedIds.value.size === cart.items.length
})

// 计算属性：是否有选中的商品
const hasSelectedItems = computed(() => {
  return selectedIds.value.size > 0
})

// 跳转到商品详情页
function goToProductDetail(item) {
  // 获取商品ID，优先使用productId或skuId
  const productId = item.productId || item.skuId || item.id
  if (productId) {
    router.push(`/product/${productId}`)
  } else {
    console.warn('无法获取商品ID，无法跳转到详情页')
  }
}

// 删除单个购物车商品
async function deleteItem(item) {
  if (item && confirm('确定要删除这个商品吗？')) {
    loading.value = true
    try {
      const { useCartStore } = await import('@/stores/cart')
      const cartStore = useCartStore()
      // 构造删除请求参数，传递商品ID数组
      const ids = [item.id || item.productId || item.skuId]
      const res = await cartStore.removeItemsApi(ids)
      
      console.log('删除购物车商品响应:', res)
      
      if (res?.code === 200) {
        // 由于store的reload方法会重新加载全部数据，这里不需要手动更新
        // 但为了UI响应更快，可以先从本地数据中移除
        const index = cart.items.findIndex(i => 
          (i.id === item.id) || (i.productId === item.productId) || (i.skuId === item.skuId)
        )
        if (index !== -1) {
          cart.items.splice(index, 1)
          saveCartDataToStorage()
        }
      } else {
        alert('删除商品失败，请重试')
      }
    } catch (error) {
      console.error('删除购物车商品错误:', error)
      if (error.code === 'ECONNREFUSED') {
        alert('无法连接到服务器，请稍后再试')
      } else if (error.response && error.response.status === 403) {
        alert('权限不足，请先登录')
        router.push('/login')
      } else {
        alert('删除商品失败: ' + (error.message || '未知错误'))
      }
    } finally {
      loading.value = false
    }
  }
}

// 加载购物车数据
async function loadCartData() {
  loading.value = true
  
  try {
    // 调用后端接口获取购物车数据
    let res
    let cartData = []
    
    try {
      res = await listCart()
      
      // 尝试获取cartItems或类似的字段 - 使用更宽松的方式查找
      if (Array.isArray(res.data)) {
        cartData = res.data
      } else if (res.data && typeof res.data === 'object') {
        // 尝试查找任何可能的商品列表字段
        const possibleFields = ['items', 'cartItems', 'products', 'goodsList', 'list', 'data', 'result', 'content']
        
        for (const field of possibleFields) {
          if (res.data[field] && Array.isArray(res.data[field])) {
            cartData = res.data[field]
            break
          }
        }
      }
      
      if (res?.code === 200 && Array.isArray(res?.data)) {
        cartData = res.data
      } else {
        cartData = []
      }
    } catch (error) {
      cartData = []
    }
    
    // 转换数据结构，确保前端能正确显示
      const formattedItems = []
      
      cartData.forEach((item, index) => {
        // 查找商品名称字段
        let productName = '未知商品'
        const nameFields = ['productName', 'title', 'name', 'product_title', 'goodsName', 'goods_name', 
                          'productname', 'itemName', 'item_name', 'product', '商品名称', '名称']
        
        // 遍历所有可能的名称字段
        for (const field of nameFields) {
          if (item[field] && typeof item[field] === 'string' && item[field].trim() !== '') {
            productName = item[field]
            break
          }
        }
        
        // 如果还是没找到，尝试任何非空字符串字段作为商品名称
        if (productName === '未知商品') {
          const allFields = Object.keys(item)
          for (const field of allFields) {
            if (item[field] && typeof item[field] === 'string' && item[field].trim() !== '') {
              productName = `${field}: ${item[field]}`
              break
            }
          }
        }
        
        // 查找价格字段（优先使用unitPrice字段）
        let price = 0
        price = Number(item.unitPrice || item.price || item.productPrice || item.goodsPrice || 0)
        
        // 查找数量字段
        let quantity = Number(item.quantity || item.qty || 0)
        
        // 查找图片字段
        let image = ''
        const imageFields = ['productImage', 'image', 'imgUrl', 'imageUrl', 'product_img', '图片']
        for (const field of imageFields) {
          if (item[field]) {
            image = item[field]
            break
          }
        }
        
        // 查找ID字段
        const id = item.id || item.productId || item.skuId || ''
        const productId = item.productId || item.id || item.skuId || ''
        
        // 添加到格式化后的数组
        formattedItems.push({
          id,
          productId,
          productName,
          productImage: image,
          price,
          quantity
        })
      })
    
    // 直接使用所有购物车数据
    cart.items = formattedItems
    
    // 保存购物车数据到localStorage
    saveCartDataToStorage()
    
    return formattedItems.length > 0
  } catch (error) {
    cart.items = []
  } finally {
    loading.value = false
  }
  return false
}

// 保存购物车数据到localStorage的辅助函数
function saveCartDataToStorage() {
  try {
    localStorage.setItem('cartItems', JSON.stringify(cart.items))
  } catch (error) {
    // 静默处理保存失败
  }
}

// 增加商品数量
async function increaseQuantity(item) {
  if (item) {
    // 计算加一后的商品数量，确保传递给后端的是更新后的值（如当前1点击后传2）
    const currentQuantity = Number(item.quantity || 0)
    const newQuantity = currentQuantity + 1
    
    console.log(`增加商品数量: 商品ID=${item.id || item.productId}, 当前数量=${currentQuantity}, 新数量=${newQuantity}`)
    await updateCartQuantity(item, newQuantity)
  }
}

// 减少商品数量
async function decreaseQuantity(item) {
  if (item && (item.quantity || 0) > 1) {
    const newQuantity = item.quantity - 1
    await updateCartQuantity(item, newQuantity)
  }
}

// 更新购物车商品数量到后端
async function updateCartQuantity(item, quantity) {
  loading.value = true
  try {
    // 构造请求参数，确保传递cartId和buyQuantity字段
    const payload = {
      cartId: item.id || item.productId || item.skuId,
      buyQuantity: quantity
    }
    
    console.log('更新购物车数量请求参数:', payload)
    const { useCartStore } = await import('@/stores/cart')
    const cartStore = useCartStore()
    const res = await cartStore.updateQtyApi(payload)
    
    console.log('更新购物车数量响应:', res)
    
    // 更新本地数据（实际应该由store的reload方法处理）
    if (res?.code === 200) {
      // 由于store的reload方法会重新加载全部数据，这里不需要手动更新
      // 但为了UI响应更快，可以先更新本地数据
      item.quantity = quantity
      saveCartDataToStorage()
    } else {
      alert('更新购物车数量失败，请重试')
    }
  } catch (error) {
    console.error('更新购物车数量错误:', error)
    if (error.code === 'ECONNREFUSED') {
      alert('无法连接到服务器，请稍后再试')
    } else if (error.response && error.response.status === 403) {
      alert('权限不足，请先登录')
      router.push('/login')
    } else {
      alert('更新购物车数量失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 从localStorage加载购物车数据
function loadCartDataFromStorage() {
  try {
    const storedData = localStorage.getItem('cartItems')
    if (storedData) {
      const items = JSON.parse(storedData)
      // 确保数据格式正确
      if (Array.isArray(items)) {
        cart.items = items.map(item => ({
          ...item,
          // 确保数量字段存在且为数字
          quantity: Number(item.quantity || item.qty || 0)
        }))
        return true
      }
    }
  } catch (error) {
    // 静默处理加载失败
  }
  return false
}

// 页面挂载时加载数据
onMounted(async () => {
  // 优先从后端加载最新数据
  const backendLoaded = await loadCartData()
  
  // 如果后端加载失败或没有数据，再尝试从localStorage加载缓存数据
  if (!backendLoaded && cart.items.length === 0) {
    loadCartDataFromStorage()
  }
})

// 计算选中商品的总价格
function calculateTotalPrice() {
  if (!hasSelectedItems.value) {
    return 0
  }
  
  return cart.items.reduce((total, item) => {
    const itemId = item.id || item.productId || item.skuId
    if (selectedIds.value.has(itemId)) {
      const price = Number(item.price || 0)
      const quantity = Number(item.quantity || item.qty || 1)
      return total + (price * quantity)
    }
    return total
  }, 0)
}

// 清空购物车
function clearAllItems() {
  if (cart.items.length > 0 && confirm('确定要清空购物车吗？')) {
    // 获取所有商品ID
    const allIds = cart.items.map(item => item.id || item.productId || item.skuId)
    deleteSelectedItems(allIds)
  }
}

// 前往首页
function goToHomePage() {
  router.push('/')
}

// 切换商品选择状态
function toggleItemSelection(item) {
  const itemId = item.id || item.productId || item.skuId
  if (selectedIds.value.has(itemId)) {
    selectedIds.value.delete(itemId)
  } else {
    selectedIds.value.add(itemId)
  }
}

// 全选/取消全选
function toggleAllSelection() {
  if (isAllSelected.value) {
    selectedIds.value.clear()
  } else {
    selectedIds.value.clear()
    cart.items.forEach(item => {
      const itemId = item.id || item.productId || item.skuId
      selectedIds.value.add(itemId)
    })
  }
}

// 购买单个商品
async function buyItem(item) {
  await createBatchOrder([item])
}

// 批量购买选中的购物车商品
async function buySelectedItems() {
  if (hasSelectedItems.value) {
    // 获取选中的商品列表
    const selectedItems = cart.items.filter(item => {
      const itemId = item.id || item.productId || item.skuId
      return selectedIds.value.has(itemId)
    })
    
    if (selectedItems.length > 0) {
      await createBatchOrder(selectedItems)
    }
  }
}

// 创建批量订单
async function createBatchOrder(selectedItems) {
  try {
    // 构建订单参数，包含所有需要在订单页面显示的商品信息
    const orderParams = {
      productList: selectedItems.map(item => ({
        productId: item.productId || item.skuId || item.id, // 优先使用productId或skuId，最后才考虑id
        productName: item.productName || '未知商品',
        productImage: item.productImage || '',
        price: item.price || 0,
        quantity: item.quantity || item.qty || 1
      })),
      // 默认值，实际应用中应该从用户收货信息中获取
      receiveName: '',
      receivePhone: '',
      receiveAddress: '',
      payType: 'ALIPAY', // 默认支付宝支付
      remark: ''
    }
    
    console.log('创建订单参数:', orderParams)
    
    // 存储订单参数到localStorage，供订单页面使用
    try {
      localStorage.setItem('pendingOrder', JSON.stringify(orderParams))
    } catch (e) {
      console.error('存储订单参数失败:', e)
    }
    
    // 跳转到订单页面
    router.push('/checkout')
  } catch (error) {
    console.error('创建订单失败:', error)
    alert('创建订单失败，请重试')
  }
}

// 批量删除购物车商品
async function deleteSelectedItems() {
  if (hasSelectedItems.value && confirm(`确定要删除选中的 ${selectedIds.value.size} 个商品吗？`)) {
    loading.value = true
    try {
      const { useCartStore } = await import('@/stores/cart')
      const cartStore = useCartStore()
      // 转换Set为数组传递给API
      const ids = Array.from(selectedIds.value)
      const res = await cartStore.removeItemsApi(ids)
      
      console.log('批量删除购物车商品响应:', res)
      
      if (res?.code === 200) {
        // 清空选中状态
        selectedIds.value.clear()
        // 由于store的reload方法会重新加载全部数据，这里不需要手动更新
        // 但为了UI响应更快，可以先从本地数据中移除
        const remainingItems = cart.items.filter(item => {
          const itemId = item.id || item.productId || item.skuId
          return !ids.includes(itemId)
        })
        cart.items = remainingItems
        saveCartDataToStorage()
      } else {
        alert('删除商品失败，请重试')
      }
    } catch (error) {
      console.error('批量删除购物车商品错误:', error)
      if (error.code === 'ECONNREFUSED') {
        alert('无法连接到服务器，请稍后再试')
      } else if (error.response && error.response.status === 403) {
        alert('权限不足，请先登录')
        router.push('/login')
      } else {
        alert('删除商品失败: ' + (error.message || '未知错误'))
      }
    } finally {
      loading.value = false
    }
  }
}
</script>

<template>
  <div class="container cart">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <h2 class="cart-title">我的购物车</h2>
      <div class="header-actions">
        <button 
          v-if="hasSelectedItems"
          class="buy-selected-btn btn-primary"
          @click="buySelectedItems"
          title="批量购买选中商品"
        >
          <i class="icon-shopping-cart"></i>
          批量购买 ({{ selectedIds.size }})
        </button>
        <button 
          v-if="hasSelectedItems"
          class="delete-selected-btn btn-danger"
          @click="deleteSelectedItems"
          title="批量删除"
        >
          <i class="icon-trash"></i>
          批量删除 ({{ selectedIds.size }})
        </button>
      </div>
    </div>
    
    <!-- 购物车内容卡片 -->
    <div class="cart-content card">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>正在加载购物车数据...</p>
      </div>
      
      <!-- 购物车表格 -->
    <div v-else class="cart-table-wrapper">
      <table class="cart-table">
        <thead>
          <tr>
            <th class="checkbox-column">
              <input 
                type="checkbox" 
                v-model="isAllSelected" 
                @change="toggleAllSelection"
                :disabled="cart.items.length === 0"
                class="custom-checkbox"
              />
            </th>
            <th class="product-info-header">商品信息</th>
            <th class="price-header">单价</th>
            <th class="quantity-header">数量</th>
            <th class="action-header">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="it in cart.items" :key="it.id || it.skuId" class="cart-item-row">
            <td class="checkbox-column">
              <input 
                type="checkbox" 
                :checked="selectedIds.has(it.id || it.productId || it.skuId)"
                @change="toggleItemSelection(it)"
                class="custom-checkbox"
              />
            </td>
            <td class="product-info">
              <div class="product-link" @click.stop="goToProductDetail(it)" :title="it.productName || it.title || it.name || '商品名称未知'">
                <div class="product-image-container">
                  <img v-if="it.productImage || it.image" :src="it.productImage || it.image" :alt="it.productName || it.title || it.name" class="product-image" />
                  <div v-else class="product-image-placeholder">{{ (it.productName || '未知商品').charAt(0) }}</div>
                </div>
                <div class="product-details">
                  <div class="product-title">{{ it.productName || it.title || it.name || '商品名称未知' }}</div>
                </div>
              </div>
            </td>
            <td v-if="it.price !== undefined" class="price">￥{{ it.price.toFixed(2) }}</td>
            <td class="quantity">
              <div class="quantity-selector">
                <button class="quantity-btn minus" @click="decreaseQuantity(it)" :disabled="(it.quantity || it.qty || 1) <= 1">-</button>
                <span class="quantity-value">{{ it.quantity || it.qty || 1 }}</span>
                <button class="quantity-btn plus" @click="increaseQuantity(it)">+</button>
              </div>
            </td>
            <td class="action">
              <button class="delete-btn btn-icon" @click="deleteItem(it)" title="删除">
                <i class="icon-trash"></i>
                <span class="btn-text">删除</span>
              </button>
              <button class="buy-btn btn-icon" @click="buyItem(it)" title="确认购买">
                <i class="icon-check"></i>
                <span class="btn-text">购买</span>
              </button>
            </td>
          </tr>
          <!-- 空购物车提示 -->
          <tr v-if="cart.items.length === 0">
            <td colspan="5" class="empty-cart">
              <div class="empty-cart-icon">
                <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="9" cy="21" r="1"></circle>
                  <circle cx="20" cy="21" r="1"></circle>
                  <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                </svg>
              </div>
              <h3>购物车还是空的</h3>
              <p>快去挑选心仪的商品吧！</p>
              <button class="btn-primary" @click="goToHomePage">去逛逛</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    </div>
    
    <!-- 购物车底部 -->
    <div v-if="cart.items.length > 0" class="cart-footer">
      <div class="cart-summary">
        <div class="selected-count">已选择 {{ selectedIds.size }} 件商品</div>
        <div class="total-price">
          <span class="price-label">合计：</span>
          <span class="price-value">￥{{ calculateTotalPrice().toFixed(2) }}</span>
        </div>
      </div>
      <div class="cart-actions">
        <button class="btn-secondary" @click="clearAllItems" v-if="cart.items.length > 0">清空购物车</button>
        <button class="btn-primary btn-lg" @click="buySelectedItems" :disabled="!hasSelectedItems">
          去结算
        </button>
      </div>
    </div>
  </div>
</template>

      if (res?.code === 200) {
        // 由于store的reload方法会重新加载全部数据，这里不需要手动更新
        // 但为了UI响应更快，可以先从本地数据中移除
        const index = cart.items.findIndex(i => 
          (i.id === item.id) || (i.productId === item.productId) || (i.skuId === item.skuId)
        )
        if (index !== -1) {
          cart.items.splice(index, 1)
          saveCartDataToStorage()
        }
      } else {
        alert('删除商品失败，请重试')
      }
    } catch (error) {
      console.error('删除购物车商品错误:', error)
      if (error.code === 'ECONNREFUSED') {
        alert('无法连接到服务器，请稍后再试')
      } else if (error.response && error.response.status === 403) {
        alert('权限不足，请先登录')
        router.push('/login')
      } else {
        alert('删除商品失败: ' + (error.message || '未知错误'))
      }
    } finally {
      loading.value = false
    }
  }
}

<style scoped>
/* 颜色变量 */
:root {
  --primary: #3498db;
  --primary-hover: #2980b9;
  --secondary: #95a5a6;
  --danger: #e74c3c;
  --danger-hover: #c0392b;
  --success: #2ecc71;
  --success-hover: #27ae60;
  --background: #f5f7fa;
  --text: #2c3e50;
  --text-light: #7f8c8d;
  --border: #e0e6ed;
  --white: #ffffff;
  --shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  --shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.12);
}

/* 购物车容器 */
.cart {
  padding: 20px 0;
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 购物车头部 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.cart-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: var(--text);
  letter-spacing: -0.5px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 通用按钮样式 */
.btn-primary {
  padding: 10px 20px;
  background: linear-gradient(135deg, var(--primary) 0%, var(--primary-hover) 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.25);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}

.btn-primary:active:not(:disabled) {
  transform: translateY(0);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-primary.btn-lg {
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
}

.btn-danger {
  padding: 10px 20px;
  background: linear-gradient(135deg, var(--danger) 0%, var(--danger-hover) 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(231, 76, 60, 0.25);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.btn-danger:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
}

.btn-secondary {
  padding: 10px 20px;
  background-color: var(--secondary);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #7f8c8d;
  transform: translateY(-1px);
}

/* 按钮图标 */
.btn-icon {
  padding: 8px 12px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.btn-text {
  font-size: 12px;
}

/* 购物车内容卡片 */
  .cart-content {
    flex: 1;
  }

  .card {
    background: var(--white);
    border-radius: 12px;
    overflow: hidden;
    box-shadow: var(--shadow);
    transition: box-shadow 0.3s ease;
  }

  .card:hover {
    box-shadow: var(--shadow-hover);
  }

  /* 加载状态 */
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;
    color: var(--text-light);
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid var(--border);
    border-top-color: var(--primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  /* 购物车表格容器 */
  .cart-table-wrapper {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
    scrollbar-color: var(--border) transparent;
  }

  .cart-table-wrapper::-webkit-scrollbar {
    height: 6px;
  }

  .cart-table-wrapper::-webkit-scrollbar-track {
    background: transparent;
  }

  .cart-table-wrapper::-webkit-scrollbar-thumb {
    background-color: var(--border);
    border-radius: 3px;
  }

  /* 购物车表格 */
  .cart-table {
    width: 100%;
    min-width: 900px; /* 确保表格有足够的最小宽度 */
    border-collapse: collapse;
    table-layout: fixed; /* 固定表格布局，确保列宽严格固定 */
  }

/* 表头样式 - 统一设置 */
th {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 12px;
  font-weight: 600;
  color: var(--text);
  text-align: center;
  border-bottom: 2px solid var(--border);
  font-size: 14px;
  letter-spacing: 0.5px;
  white-space: nowrap;
  vertical-align: middle;
  height: 48px;
}

/* 复选框列 - 表头和内容行统一设置 */
th.checkbox-column, td.checkbox-column {
  width: 60px;
  min-width: 60px;
  text-align: center;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 商品信息列 - 表头和内容行统一设置 */
th.product-info-header, td.product-info {
  width: 300px;
  min-width: 300px;
  text-align: left;
  padding: 0;
}

/* 商品信息内容优化 */
.product-details {
  flex: 1;
  min-width: 0;
}

.product-title {
  font-weight: 500;
  color: var(--text);
  font-size: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.2s ease;
  word-break: break-word;
  text-align: left;
}

/* 价格列 - 表头和内容行统一设置 */
th.price-header, td.price {
  width: 120px;
  min-width: 120px;
  text-align: right;
  padding: 0 30px 0 0;
}

/* 数量列 - 表头和内容行统一设置 */
th.quantity-header, td.quantity {
  width: 150px;
  min-width: 150px;
  text-align: center;
  padding: 0;
}

/* 操作列 - 表头和内容行统一设置 */
th.action-header, td.action {
  width: 160px;
  min-width: 160px;
  text-align: center;
  padding: 0;
}

/* 表头悬停效果 */
th::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, var(--primary), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

th:hover::after {
  opacity: 0.5;
}

/* 自定义复选框 */
.custom-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: var(--primary);
  border-radius: 4px;
}

/* 购物车商品行 */
.cart-item-row {
  transition: all 0.3s ease;
  position: relative;
  height: 132px;
}

.cart-item-row:hover {
  background-color: #f8f9ff;
}

.cart-item-row::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--primary);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cart-item-row:hover::before {
  opacity: 1;
}

/* 表格单元格基础样式 */
td {
  padding: 16px 0;
  text-align: center;
  border-bottom: 1px solid var(--border);
  vertical-align: middle;
  transition: background-color 0.3s ease;
}

.product-link {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.product-link:hover {
  transform: translateX(2px);
}

.product-image-container {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.product-link:hover .product-image-container {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  transform: scale(1.03);
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-image-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary);
  font-size: 32px;
  font-weight: 700;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-title {
  font-weight: 500;
  color: var(--text);
  font-size: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.2s ease;
}

.product-link:hover .product-title {
  color: var(--primary);
}

/* 价格样式 */
.price {
  color: var(--danger);
  font-weight: 700;
  font-size: 18px;
  letter-spacing: 0.5px;
  transition: color 0.2s ease;
  text-align: right; /* 价格右对齐 */
}

/* 数量选择器 */
.quantity-selector {
  display: flex;
  align-items: center;
  gap: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  background-color: white;
  min-width: 140px;
  margin: 0 auto; /* 居中显示 */
}

.quantity-btn {
  width: 40px;
  height: 40px;
  border: none;
  background-color: #f8f9fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
  color: var(--text-light);
  transition: all 0.3s ease;
  user-select: none;
}

.quantity-btn:hover:not(:disabled) {
  background-color: var(--primary);
  color: white;
}

.quantity-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.quantity-value {
  min-width: 60px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: var(--text);
  background-color: white;
  border-top: 1px solid var(--border);
  border-bottom: 1px solid var(--border);
  padding: 10px 0;
  line-height: 20px;
}

/* 操作按钮 */
.action {
  text-align: center;
  white-space: nowrap;
  padding: 12px 8px;
  min-width: 160px;
  width: 160px;
}

.delete-btn {
  background-color: #fff;
  color: var(--danger);
  border: 1px solid #ffd7d7;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-bottom: 8px;
  display: block;
  width: 100%;
  padding: 8px 12px;
}

.delete-btn:hover {
  background-color: var(--danger);
  color: white;
  border-color: var(--danger);
}

.buy-btn {
  background-color: #fff;
  color: var(--success);
  border: 1px solid #d7ffd7;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  display: block;
  width: 100%;
  padding: 8px 12px;
}

.buy-btn:hover {
  background-color: var(--success);
  color: white;
  border-color: var(--success);
}

/* 空购物车状态 */
.empty-cart {
  text-align: center;
  padding: 100px 20px;
  color: var(--text-light);
  font-size: 16px;
}

.empty-cart-icon {
  margin-bottom: 24px;
  opacity: 0.6;
  transition: opacity 0.3s ease;
}

.empty-cart:hover .empty-cart-icon {
  opacity: 1;
}

.empty-cart h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--text);
}

.empty-cart p {
  margin: 0 0 24px 0;
  color: var(--text-light);
}

/* 购物车底部 */
.cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: var(--shadow);
    margin-top: 20px;
    flex-wrap: wrap;
    gap: 16px;
  }

  .cart-summary {
    display: flex;
    align-items: center;
    gap: 24px;
    flex-wrap: wrap;
  }

.selected-count {
  font-size: 14px;
  color: var(--text);
}

.total-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.price-label {
  font-size: 14px;
  color: var(--text);
}

.price-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--danger);
}

.cart-actions {
  display: flex;
  gap: 12px;
}

/* 图标样式 */
.icon-shopping-cart::before {
  content: '🛒';
}

.icon-trash::before {
  content: '🗑️';
}

.icon-check::before {
  content: '✓';
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .cart-table {
    display: block;
    overflow-x: auto;
  }
  
  .product-info {
    min-width: 200px;
  }
  
  .product-image-container {
    width: 80px;
    height: 80px;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 16px;
  }
  
  .cart-summary {
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
  
  .cart-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>


